<?php

namespace Someline\Console;

use Illuminate\Console\Scheduling\Schedule;
use DB;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
use Someline\Component\Wechat\SomelineWechatService;


class Kernel extends ConsoleKernel
{
    /**
     * The Artisan commands provided by your application.
     *
     * @var array
     */
    protected $commands = [
        //
    ];

    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {

        $schedule->exec(
            $schedule->call(
                function () {

                    // for ($p=0;$p<60;$p++){

                    $app = SomelineWechatService::getWechatApplication();
                    $material = $app->material;

                    $list_offset = 0;
                    $list_count = 20;

                    $lists = $material->lists('news', $list_offset, $list_count);

                    $lists = $lists->toArray();

                    $total_count = $lists['total_count'];

                    $forNum = $total_count / $list_count;

                    //$datetime = new \DateTime;
                    //$time = $datetime->format('Y-m-d H:i:s');

                    for ($i = 0; $i < $forNum; $i++) {

                        $list_offset = $i * $list_count;

                        $lists = $material->lists('news', $list_offset, $list_count);

                        $lists = $lists->toArray();
                        //print_r($lists['item'][1]);

                        foreach ($lists['item'] as $item) {

                            $content = $item['content']['news_item'][0];

                                        $sql = "INSERT INTO  `wfx_wx_tw` (`acount_id`, `media_id`, `pic_addr`, `title`, `author`, `desc`, `url`) 
        SELECT 3,
        '" . $item['media_id'] . "',
        '" . $content['thumb_url'] . "',
        '" . $content['title'] . "',
        '" . $content['author'] . "',
        '" . $content['digest'] . "',
        '" . $content['url'] . "' FROM dual  
        WHERE not exists (select * from `wfx_wx_tw`  where acount_id = 1 and title = '" .$content['title']. "' )";
                                        //print_r($sql);
                                        DB::statement($sql);



                        }
                    }
                } //function
            )->everyMinute()

        )->daily();

    }

    /**
     * Register the Closure based commands for the application.
     *
     * @return void
     */
    protected function commands()
    {
        require base_path('routes/console.php');
    }
}
